import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { Menu } from 'antd'
import type { MenuProps } from 'antd'
type MenuItem = Required<MenuProps>['items'][number]

// 对侧边栏的值进行约束
function getItem(
  // 名称
  label: React.ReactNode,
  // 路径
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem
}

// 侧边栏的数组
const items: MenuItem[] = [
  getItem('about 1', '/about', <PieChartOutlined />),
  getItem('page 2', '/page', <DesktopOutlined />),
  getItem('User', 'sub', <UserOutlined />, [
    getItem('Tom', '/sub/com1'),
    getItem('Bill', '/sub/com2'),
    getItem('Alex', '/sub/com3'),
  ]),
  getItem('Team', 'sub2', <TeamOutlined />, [
    getItem('Team 1', '6'),
    getItem('Team 2', '8'),
  ]),
]

const MainMenu = () => {
  // 拿到当前所在的路由地址
  const currentRoute = useLocation()
  // 用于接收展开的 menu 值
  let openSub: string = ''

  // 遍历 items，拿到当前展开的父节点 menu 值
  for (let i = 0; i < items.length; i++) {
    // @ts-ignore
    const element: { key: string; children: [] } | null = items[i]
    // 判断有无 children，拿当前子路由跟 children 里面 key 值进行匹配
    if (
      element?.children &&
      element?.children.length > 1 &&
      element?.children.find(
        (item: { key: string }) => item.key === currentRoute.pathname,
      )
    ) {
      console.log('结果', element)
      // 拿到展开的 key，给 openSub 进行展开 menu
      openSub = element?.key
      break
    }
  }

  // 设置展开项的初始值
  const [openKeys, setOpenKeys] = useState([openSub])
  // 接收返回的跳转
  const navigateTo = useNavigate()

  // 点击菜单栏触发
  const mentClick = (e: { key: string }) => {
    // key 路由路径
    // navigateTo 跳转
    navigateTo(e.key)
  }

  // keys 记录当前展开的 menu
  const hadleOpenChange = (keys: string[]) => {
    console.log(keys)
    // 将最后一个展开的 menu 值给 openKeys 进行展开，之前进行收起
    setOpenKeys([keys[keys.length - 1]])
  }

  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={[currentRoute.pathname]}
      mode="inline"
      items={items}
      onClick={mentClick}
      // 菜单打开和回收触发
      onOpenChange={hadleOpenChange}
      openKeys={openKeys}
    />
  )
}

export default MainMenu
